package handler

import (
	"2212b/2212ay1/api/request"
	"2212b/2212ay1/global"
	"2212b/2212ay1/internal/dao"
	"2212b/2212ay1/internal/model"
	"github.com/gin-gonic/gin"
	"net/http"
)

func SendDamu(c *gin.Context) {
	var req request.SendDamuReq

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "参数验证失败",
			"data": err.Error(),
		})
		return
	}
	//1.视频是否存在
	var video model.Video
	dao.GetOneById(req.VideoId, &video)
	if video.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "视频不存在",
			"data": nil,
		})
		return
	}
	//2.保存弹幕
	tx := global.DB.Begin() //开启一个事务
	err := tx.Create(&model.Damu{
		VideoId: c.GetUint("userId"),
		Modes:   req.Modes,
		Text:    req.Text,
		Stime:   req.Stime,
		Size:    req.Size,
		Color:   req.Color,
	})
	if err != nil {
		tx.Rollback() //在事务中做一些数据库操作
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "保存弹幕失败",
			"data": nil,
		})
		return
	}
	//3.更新视频表弹幕数量
	tx.Model(model.Video{}).Updates(&model.Video{Id: video.Id, DamuNum: video.DamuNum + 1})

	if err := tx.Model(model.Video{}).Updates(&model.Video{Id: video.Id, DamuNum: video.DamuNum + 1}).Error; err != nil {
		tx.Rollback() //发生错误时回滚事务
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "弹幕保存失败",
			"data": nil,
		})
		return
	}
	tx.Commit() //提交事务
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "弹幕发布成功",
		"data": true,
	})
}
